package com.ysxsoft.wdg.ui.activity.address;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.AddressBean;
import com.ysxsoft.wdg.bean.BannerBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.JsonBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.util.GetJsonDataUtil;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.ysxsoft.wdg.widget.alertview.OnItemClickListener;

import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class AddressEditActivity extends BaseActivity {



    public static void start(Context context, int code, AddressBean addressBean){
        Intent intent = new Intent(context,AddressEditActivity.class);
        intent.putExtra("code",code);
        if (code != -1) {
            intent.putExtra("address", addressBean);
        }
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.et_address_name)
    EditText etAddressName;
    @BindView(R.id.et_address_tel)
    EditText etAddressTel;
    @BindView(R.id.et_address_ssq)
    TextView etAddressSsq;
    @BindView(R.id.ll_ssq)
    LinearLayout llSsq;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;

    private int code = -1;
    private AddressBean addressBean;
    private String aid = "",uid = "",province="",city = "",county = "",name = "",phone ="",address = "";


    @Override
    protected int getLayoutId() {
        return R.layout.activity_address_edit;
    }

    @Override
    protected void initData() {
        initStatusBar(topView,false);
        titleContent.setText("地址管理");

        uid = SharePrefUtils.getUserId();
        handler.sendEmptyMessage(MSG_LOAD_DATA);

        Intent intent = getIntent();
        code = intent.getIntExtra("code",-1);
        if (code != -1){
            addressBean = intent.getParcelableExtra("address");

            aid = addressBean.getId();
            etAddressName.setText(addressBean.getName());
            etAddressTel.setText(addressBean.getPhone());
            etAddressDetail.setText(addressBean.getAddress());
            province = addressBean.getProvince();
            city = addressBean.getCity();
            county = addressBean.getCounty();
            etAddressSsq.setText(province+city+county);
        }
    }

    @Override
    protected void setListener() {

    }


    @OnClick({R.id.title_finish, R.id.ll_ssq, R.id.btn_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.ll_ssq:
                ViewUtils.closeKeyboard(this);
                selectAddress();
                break;
            case R.id.btn_sure:
                name = etAddressName.getText().toString().trim();
                phone = etAddressTel.getText().toString().trim();
                address = etAddressDetail.getText().toString().trim();

                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(address) || TextUtils.isEmpty(province)){
                    ToastUtils.showToast("不能为空");
                    return;
                }

                if(phone.length()!=11){
                    ToastUtils.showToast("手机号格式不正确!");
                    return;
                }

                if (code == -1){//添加新地址
                    addAdress();
                }else {//编辑地址
                    editAddress();
                }
                break;
        }
    }

    private void editAddress() {
        mApiHelper.editAddress(aid, province, city, county, address, name, phone, "0", new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                ToastUtils.showToast(baseBean.getMs());
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void addAdress() {
        mApiHelper.addAddress(uid, province, city, county, address, name, phone, "0", new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                ToastUtils.showToast(baseBean.getMs());
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }


    //地址选择器
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {


                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        //                        Toast.makeText(RealNameActivity.this,"开始解析数据",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据成功",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    /**
     * 城市三级联动
     */
    private void selectAddress() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                province =options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
                county = options3Items.get(options1).get(options2).get(options3);

                etAddressSsq.setText(province+city+county);

            }
        }).setDividerColor(Color.GRAY)
                .setCancelColor(R.color.red_color)
                .setSubmitColor(R.color.red_color)
                //.setTextColorCenter(getResources().getColor(R.color.blue)) //设置选中项文字颜色
                .setContentTextSize(16)
                //.setTitleText("城市选择")
                .setOutSideCancelable(true)// default is true
                .build();
        //默认选择河南省
        pvOptions.setSelectOptions(15);
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }




    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
